<template>
  <div class="com-container">
    <div ref="type_ref" class="com-chart" />
  </div>
</template>

<script>
import { getFullTag } from '@/api/common/common'

export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: '分类数据'
    }
  },
  data() {
    return {
      typeList: [],
      data: [],
      chartInstance: null
    }
  },
  mounted() {
    this.initChart()
    this.getData()
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  methods: {
    screenAdapter() {
      this.chartInstance.resize()
    },
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.type_ref, this.theme)
      const initOption = {
        title: {
          text: this.title
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '3',
          data: ['Industries', 'Technology', 'Forex', 'Gold', 'Forecasts']
        },
        series: [
          {
            name: '分类',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            data: [
              { value: 320, name: 'Industries' },
              { value: 240, name: 'Technology' },
              { value: 149, name: 'Forex' },
              { value: 100, name: 'Gold' },
              { value: 59, name: 'Forecasts' }
            ],
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      }
      this.chartInstance.setOption(initOption)
    },
    compare(property) {
      return function(a, b) {
        const value1 = a[property]
        const value2 = b[property]
        return value2 - value1
      }
    },
    async getData() {
      if (this.url !== '') {
        await getFullTag(this.url).then(response => {
          this.typeList = response.sort(this.compare('total'))
          this.data = this.typeList.map(item => {
            return { name: item['name'], value: item['total'] }
          })
        })
        const dataOption = {
          legend: {
            data: this.data.map(item => item['name'])
          },
          series: [{
            data: this.data
          }]
        }
        await this.chartInstance.setOption(dataOption)
        // console.log(this.data)
      }
    }
  }
}
</script>

<style scoped>

    .com-container {
        width: 100%;
        height: 350px;
        overflow: hidden;
    }

    .com-chart {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    canvas {
        border-radius: 0;
    }
</style>
